<template>
  <div class="relative">
    <!-- 输入区域容器 -->
    <div class="bg-white border border-gray-200 rounded-xl shadow-sm focus-within:border-primary-500 focus-within:ring-2 focus-within:ring-primary-100 transition-all duration-200">
      <!-- 输入框和发送按钮 -->
      <div class="flex items-end p-3">
        <!-- 输入框 -->
        <div class="flex-1 relative">
          <textarea
            ref="textareaRef"
            v-model="inputValue"
            :placeholder="placeholder"
            :disabled="disabled"
            @keydown="handleKeydown"
            @input="handleInput"
            @focus="handleFocus"
            @blur="handleBlur"
            class="w-full px-0 py-2 border-0 resize-none focus:outline-none disabled:bg-transparent disabled:cursor-not-allowed text-gray-900 placeholder-gray-500"
            :class="{
              'text-red-600': hasError
            }"
            rows="1"
            :maxlength="maxLength"
          />
          
          <!-- 字符计数 -->
          <div v-if="showCharCount" class="absolute bottom-1 right-2 text-xs text-gray-400">
            {{ inputValue.length }}/{{ maxLength }}
          </div>
        </div>
        
        <!-- 发送按钮 -->
        <button
          @click="handleSend"
          :disabled="!canSend"
          class="ml-3 w-8 h-8 bg-primary-600 hover:bg-primary-700 disabled:bg-gray-300 disabled:cursor-not-allowed text-white rounded-lg flex items-center justify-center transition-all duration-200 hover:scale-105 disabled:hover:scale-100"
          :class="{ 'animate-pulse': disabled }"
        >
          <svg v-if="!disabled" class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
          </svg>
          <svg v-else class="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
          </svg>
        </button>
      </div>
      
      <!-- 快捷操作按钮 -->
      <Transition
        enter-active-class="transition-all duration-300 ease-out"
        enter-from-class="opacity-0 transform -translate-y-2"
        enter-to-class="opacity-100 transform translate-y-0"
        leave-active-class="transition-all duration-200 ease-in"
        leave-from-class="opacity-100 transform translate-y-0"
        leave-to-class="opacity-0 transform -translate-y-2"
      >
        <div v-if="showQuickActions && isFocused && !inputValue.trim()" class="px-3 pb-3">
          <div class="flex flex-wrap gap-2">
            <button
              v-for="action in quickActions"
              :key="action.label"
              @click="insertQuickAction(action.text)"
              @mousedown.prevent
              class="text-xs px-3 py-1.5 bg-gray-50 hover:bg-primary-50 hover:text-primary-700 text-gray-600 rounded-lg border border-gray-200 hover:border-primary-200 transition-all duration-200 hover:shadow-sm active:scale-95 focus:outline-none focus:ring-2 focus:ring-primary-200"
              type="button"
            >
              {{ action.label }}
            </button>
          </div>
        </div>
      </Transition>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="hasError" class="mt-2 text-xs text-red-500 flex items-center">
      <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      {{ errorMessage }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'

interface Props {
  placeholder?: string
  disabled?: boolean
  maxLength?: number
  showCharCount?: boolean
  showQuickActions?: boolean
}

interface QuickAction {
  label: string
  text: string
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: 'Ask about prompts, styles, or techniques...',
  disabled: false,
  maxLength: 1000,
  showCharCount: false,
  showQuickActions: true
})

const emit = defineEmits<{
  send: [message: string]
  typing: [isTyping: boolean]
}>()

// 响应式状态
const inputValue = ref('')
const isFocused = ref(false)
const hasError = ref(false)
const errorMessage = ref('')
const textareaRef = ref<HTMLTextAreaElement>()

// 快捷操作
const quickActions: QuickAction[] = [
  { label: '文生图', text: 'Create a beautiful sunset over the ocean with sailboats' },
  { label: '图生图', text: 'Transform this image into a watercolor painting style' },
  { label: '人像生成', text: 'Generate a professional headshot portrait' },
  { label: '质量提升', text: 'Enhance the resolution and details of this image' }
]

// 计算属性
const canSend = computed(() => {
  return inputValue.value.trim().length > 0 && !props.disabled
})

// 方法
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    handleSend()
  }
}

const handleInput = () => {
  // 自动调整高度
  adjustTextareaHeight()
  
  // 发送打字状态
  emit('typing', inputValue.value.length > 0)
  
  // 清除错误状态
  if (hasError.value) {
    hasError.value = false
    errorMessage.value = ''
  }
}

const handleFocus = () => {
  isFocused.value = true
  hasError.value = false
}

const handleBlur = () => {
  isFocused.value = false
  emit('typing', false)
}

const handleSend = () => {
  if (!canSend.value) return
  
  const message = inputValue.value.trim()
  if (message.length === 0) return
  
  // 验证消息长度
  if (message.length > props.maxLength) {
    hasError.value = true
    errorMessage.value = `消息长度不能超过 ${props.maxLength} 个字符`
    return
  }
  
  // 发送消息
  emit('send', message)
  
  // 清空输入框
  inputValue.value = ''
  adjustTextareaHeight()
  
  // 清除错误状态
  hasError.value = false
}

const insertQuickAction = (text: string) => {
  // 如果输入框已有内容，在末尾添加空格和文本
  if (inputValue.value.trim()) {
    inputValue.value = inputValue.value.trim() + ' ' + text
  } else {
    inputValue.value = text
  }
  
  // 调整高度并聚焦
  adjustTextareaHeight()
  
  // 使用nextTick确保DOM更新后再聚焦
  nextTick(() => {
    textareaRef.value?.focus()
    // 将光标移动到文本末尾
    if (textareaRef.value) {
      const length = textareaRef.value.value.length
      textareaRef.value.setSelectionRange(length, length)
    }
  })
}

const adjustTextareaHeight = () => {
  nextTick(() => {
    if (textareaRef.value) {
      textareaRef.value.style.height = 'auto'
      const scrollHeight = textareaRef.value.scrollHeight
      const maxHeight = 120 // 最大高度
      textareaRef.value.style.height = Math.min(scrollHeight, maxHeight) + 'px'
    }
  })
}

// 监听输入值变化，自动调整高度
watch(inputValue, () => {
  adjustTextareaHeight()
})
</script>
